package com.globalwave.filemanage.thumbnail;

import java.io.File;
import java.io.IOException;

import javax.activation.MimetypesFileTypeMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.globalwave.filemanage.FMCodeHelper;
import com.globalwave.filemanage.entity.Document;

/**
 * Manager class used to handle document thumbnails
 * 
 * @author Marco Meschieri - Logical Objects
 * @since 4.5
 */
public class ThumbnailManager {
	protected static Log log = LogFactory.getLog(ThumbnailManager.class);


	/**
	 * Creates the thumbnail for the specified document and file version
	 * 
	 * @param document The document to be treated
	 * @param fileVersion The file version(optional)
	 * @throws IOException
	 */
	public void createTumbnail(Document document, String fileVersion) throws Exception {
		ThumbnailBuilder builder = getBuilder(document.getType_());
		
		if (builder == null) {
			log.warn("No registered thumbnail for extension " + document.getType_());
			try {
				//MagicMatch match = Magic.getMagicMatch(documentManager.getDocumentFile(document), true);
				//if ("text/plain".equals(match.getMimeType())) {

				File f = new File("gumby.gif"); 
				String mimeType = new MimetypesFileTypeMap().getContentType(f);

				if ("text/plain".equals(mimeType)) {
					log.warn("Try to convert as plain text");
					builder = getBuilder("txt");
					if (builder == null) {
						return ;
					}
				} else {
					return;
				}
			} catch (Exception e) {
				return;
			}
		}

		int size = FMCodeHelper.getInteger("gui.thumbnail.size");

		float quality = FMCodeHelper.getFloat("gui.thumbnail.quality");

		int scaleAlgorithm = FMCodeHelper.getInteger("gui.thumbnail.scale");


		try {
			String fver = fileVersion;
			if (fver == null)
				fver = String.valueOf(document.getVersion_());
			File src = new File(document.getFolderPath() + "/" + document.getDocument_id());
			File dest = new File(document.getFolderPath() + "/thumbs/" + document.getDocument_id());
			builder.build(src, document.getName_(), size, dest, scaleAlgorithm, quality);
		} catch (Exception e) {
			log.error(e.getMessage(), e) ;
			log.warn("Error creating thumbnail for document: " + document.getTitle_());
		}
	}

	/**
	 * Creates the thumbnail for the specified document
	 * 
	 * @param document The document to be treated
	 * @throws IOException
	 */
	public void createTumbnail(Document document) throws Exception {
		createTumbnail(document, null);
	}

	public ThumbnailBuilder getBuilder(String type) {

		
		try {
			return (ThumbnailBuilder)Class.forName(
					(String)FMCodeHelper.getThumbnailMap().get(type)).newInstance();
		} catch(Exception e) {
			log.error(e.getMessage(), e) ;
			return null;
		}
	}
}